package org.example.order.facade;

import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.DubboService;
import org.example.api.goods.request.GoodsSaleRequest;
import org.example.api.goods.response.GoodsSaleResponse;
import org.example.api.goods.service.GoodsFacadeService;
import org.example.api.inventory.service.InventoryFacadeService;
import org.example.api.order.OrderFacadeService;
import org.example.api.order.model.TradeOrderVO;
import org.example.api.order.request.*;
import org.example.api.order.response.OrderResponse;
import org.example.api.user.serivce.UserFacadeService;
import org.example.base.response.BaseResponse;
import org.example.base.response.PageResponse;
import org.example.base.response.SingleResponse;
import org.example.order.OrderException;
import org.example.order.domain.entity.TradeOrder;
import org.example.order.domain.service.OrderManageService;
import org.example.order.domain.service.OrderReadService;
import org.example.order.validator.OrderCreateValidator;
import org.example.rpc.facade.Facade;
import org.example.stream.producer.StreamProducer;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ThreadPoolExecutor;

import static org.example.api.order.constant.OrderErrorCode.ORDER_CREATE_VALID_FAILED;

@DubboService(version = "1.0.0")
public class OrderFacadeServiceImpl implements OrderFacadeService {

    @Autowired
    private OrderManageService orderService;

    @Autowired
    private OrderReadService orderReadService;

    @Autowired
    private InventoryFacadeService inventoryFacadeService;

    @Autowired
    private StreamProducer streamProducer;

    @Autowired
    private UserFacadeService userFacadeService;

    @Autowired
    private GoodsFacadeService goodsFacadeService;

    @Autowired
    private OrderCreateValidator orderValidatorChain;

    @Autowired
    private OrderCreateValidator orderConfirmValidatorChain;

    @Autowired
    private ThreadPoolExecutor newBuyConsumePool;


    public void setPool(int core, int max) {
        newBuyConsumePool.setMaximumPoolSize(max);
        newBuyConsumePool.setCorePoolSize(core);
    }

    @Override
    public OrderResponse create(OrderCreateRequest request) {
        return null;
    }

    @Override
    public OrderResponse cancel(OrderCancelRequest request) {
        return sendTransactionMsgForClose(request);
    }

    @Override
    @Facade
    public OrderResponse timeout(OrderTimeoutRequest request) {
        return sendTransactionMsgForClose(request);
    }

    @Override
    @Facade
    public OrderResponse confirm(OrderConfirmRequest request) {
        GoodsSaleRequest goodsSaleRequest = new GoodsSaleRequest();
        goodsSaleRequest.setUserId(request.getBuyerId());
        goodsSaleRequest.setGoodsId(Long.valueOf(request.getGoodsId()));
        goodsSaleRequest.setGoodsType(request.getGoodsType().name());
        goodsSaleRequest.setIdentifier(request.getOrderId());
        goodsSaleRequest.setQuantity(request.getItemCount());
        BaseResponse response = goodsFacadeService.sale(goodsSaleRequest);

        if (response.getSuccess()) {
            return orderService.confirm(request);
        }

        return new OrderResponse.OrderResponseBuilder().orderId(request.getOrderId()).buildFail(response.getResponseCode(), response.getResponseMessage());
    }

    @Override
    public OrderResponse createAndConfirm(OrderCreateAndConfirmRequest request) {
        try {
            orderConfirmValidatorChain.validate(request);
        } catch (OrderException e) {
            return new OrderResponse.OrderResponseBuilder().orderId(request.getOrderId()).buildFail(ORDER_CREATE_VALID_FAILED.getCode(), e.getErrorCode().getMessage());
        }
        // 是否同步扣减库存
        if (request.isSyncDecreaseInventory()) {
            GoodsSaleRequest goodsSaleRequest = new GoodsSaleRequest(request);
            GoodsSaleResponse response = goodsFacadeService.saleWithoutHint(goodsSaleRequest);
            if (!response.getSuccess()) {
                return new OrderResponse.OrderResponseBuilder().buildFail(response.getResponseMessage(), response.getResponseCode());
            }
        }
        return orderService.createAndConfirm(request);
    }

    @Override
    public OrderResponse paySuccess(OrderPayRequest request) {
        return null;
    }

    @Override
    public SingleResponse<TradeOrderVO> getTradeOrder(String orderId) {
        return null;
    }

    @Override
    public SingleResponse<TradeOrderVO> getTradeOrder(String orderId, String userId) {
        return null;
    }

    @Override
    public PageResponse<TradeOrderVO> pageQuery(OrderPageQueryRequest request) {
        return null;
    }


    @NotNull
    private OrderResponse sendTransactionMsgForClose(BaseOrderUpdateRequest request) {
        //消息监听：TradeOrderListener
        streamProducer.send("orderClose-out-0", null, JSON.toJSONString(request), "CLOSE_TYPE", request.getOrderEvent().name());
        TradeOrder tradeOrder = orderReadService.getOrder(request.getOrderId());
        OrderResponse orderResponse = new OrderResponse();
        if (tradeOrder.isClosed()) {
            orderResponse.setSuccess(true);
        } else {
            orderResponse.setSuccess(false);
        }
        return orderResponse;
    }
}
